﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PMSGSC.Common;
using DevExpress.XtraEditors;
using PMSGSC.DAL;
using PMSGSC.BLL;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Controls;
using System.Globalization;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data.Linq;
using DevExpress.Utils.OAuth.Provider;
using DevExpress.XtraRichEdit.Model;
using System.Diagnostics;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraTab;
using DevExpress.XtraBars;


namespace PMSGSC.App
{
    public partial class frmRequistionWork : DevExpress.XtraEditors.XtraForm
    {
        WorkOrder workOrder;
        frmMain main;
        public frmRequistionWork(frmMain objMain)
        {
            InitializeComponent();
            workOrder = workOrderBindingSource.AddNew() as WorkOrder;
            workOrder.CreateDate = DateTime.Now.Date;
            int CountworkOrder = WorkOrder_BLL.GetQuantityWorkOrder(frmMain.ship.Ship_ID);
            workOrder.WorkOrderNumber = frmMain.ship.CodeShip + "/" + GetYear(DateTime.Now.Date.Year) + "/" + CountworkOrder.ToString();
            workOrder.EmployeeCreate = frmMain.UserLogin.Name;
            main = objMain;

        }

        public frmRequistionWork(frmMain objMain, int id)
        {
            InitializeComponent();
            workOrder = workOrderBindingSource.AddNew() as WorkOrder;

            workOrder.CreateDate = DateTime.Now.Date;
            int CountworkOrder = WorkOrder_BLL.GetQuantityWorkOrder(frmMain.ship.Ship_ID);
            workOrder.WorkOrderNumber = frmMain.ship.CodeShip + "/" + GetYear(DateTime.Now.Date.Year) + "/" + CountworkOrder.ToString();
            workOrder.EmployeeCreate = frmMain.UserLogin.Name;
            ucLoadEquipment1.SetValueBeforeInsert(id);
            main = objMain;
        }

        private int GetYear(int year)
        {
            return year % 1000;
        }
        private void InsertWO()
        {
            if (ucLoadEquipment1.lbid.Text == "")
            {
                XtraMessageBox.Show("Component not empty", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            frmProcessBar pb = new frmProcessBar();
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                LoadSkinToForm();
                pb.ShowDialog();
            }
            ));
            thread.Start();
            if (workOrder.Title == null && ucLoadworkOrderDescription1.lbid.Text != "")
            {
                workOrder.Title = ucLoadworkOrderDescription1.txtCode.Text + " - " + ucLoadworkOrderDescription1.txtName.Text;
            }
            SetValue();

            bool result = WorkOrder_BLL.Insert(workOrder);
            if (attachmentWorkOrderBindingSource.Count > 0)
            {
                WorkOrder newworkOrder = WorkOrder_BLL.GetLastWorkOrder();
                foreach (AttachmentWorkOrder a in attachmentWorkOrderBindingSource.Cast<AttachmentWorkOrder>().ToList())
                {
                    a.WorkOrder_ID = newworkOrder.WorkOrder_ID;
                    bool r = AttachmentWorkOrder_BLL.Insert(a);
                }
            }

            List<WorkOrder> workOrderList = new List<WorkOrder>();
            workOrderList.Add(workOrder);

            frmWorkOrderDeatails workOrderDetails = new frmWorkOrderDeatails(workOrderList, main);
            workOrderDetails.MdiParent = main;
            workOrderDetails.Show();

            this.Close();

            if (pb.InvokeRequired)
                pb.BeginInvoke(new Action(() => pb.Close()));
        }

        private void SetValue()
        {
            workOrder.StatusJob_ID = 2;
            workOrder.Type = 2;
            workOrder.Complete = false;
            workOrder.IsCheck = false;
            workOrder.Ship_ID = frmMain.ship.Ship_ID;
            workOrder.Equipment_ID = int.Parse(ucLoadEquipment1.lbid.Text);
            if (causeMemoEdit.ContainsFocus)
            {
                workOrder.Cause = causeMemoEdit.Text;
            }
            if (actionTakenMemoEdit.ContainsFocus)
            {
                workOrder.ActionTaken = actionTakenMemoEdit.Text;
            }
            if (effectMemoEdit.ContainsFocus)
            {
                workOrder.OverdueReason = effectMemoEdit.Text;
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            InsertWO();
        }

        private void employee_IDGridLookUpEdit_QueryPopUp(object sender, CancelEventArgs e)
        {
            if (employeeBindingSource.Count == 0)
            {
                employeeBindingSource.DataSource = Employee_BLL.GetAll(frmMain.ship.Ship_ID);
            }
        }

        #region Attachment workOrder

        // Khai báo trạng thái mặc định 
        private Status statusAttachmentworkOrder = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private AttachmentWorkOrder attachmentworkOrder = new AttachmentWorkOrder();
        //Hiển thị số thứ tự của gridview

        private void gridViewAJ_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private bool isChangedAJ;
        private void attachmentsworkOrderBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedAJ = true;
        }
        private void attachmentsworkOrderBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            attachmentworkOrder = attachmentWorkOrderBindingSource.Current as AttachmentWorkOrder;
        }

        private void btnUploadFileAJ_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Select one file upload";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog.InitialDirectory + openFileDialog.FileName;
                FileInfo fileInfo = new FileInfo(fileName);
                long sizeFile = fileInfo.Length / 1000;
                if (sizeFile <= 3000)
                {

                    string extension = Path.GetExtension(fileName);
                    attachmentworkOrder.Extension = extension;
                    byte[] fileByteArray = StreamFile(fileName);
                    // Converts it to Binary
                    // it can be done inside the method as well
                    Binary fileBinary = new Binary(fileByteArray);
                    attachmentworkOrder.ContentFile = fileBinary;
                    GridColumn AttachExtension = gridView18.Columns["Extension"];
                    extension = extension.ToUpper();
                    gridView18.SetRowCellValue(gridView18.FocusedRowHandle, AttachExtension, extension);
                }
                else
                {
                    XtraMessageBox.Show("The size file  must be less than 3M ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private byte[] StreamFile(string fileName)
        {
            // Open file
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // ByteArray
            byte[] ImageData = new byte[fs.Length];

            // Read block of bytes
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

            // Close it
            fs.Close();

            // Return the byte data
            return ImageData;
        }

        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewAJ_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveAttachmentworkOrderToDatabase();
        }

        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Office 2007 Blue");
            }
        }

        private void SaveAttachmentworkOrderToDatabase()
        {

        }
        private void DeleteAttachmentworkOrder(NavigatorButtonClickEventArgs e)
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                bool result = AttachmentWorkOrder_BLL.Delete(attachmentworkOrder);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                attachmentWorkOrderBindingSource.DataSource = AttachmentWorkOrder_BLL.GetDataByworkOrderID(workOrder.WorkOrder_ID, isChangedAJ);
                isChangedAJ = false;
            }
            e.Handled = true;
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridViewAJ_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    bool result = AttachmentWorkOrder_BLL.Delete(attachmentworkOrder);
                    if (!result)
                    {
                        XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    attachmentWorkOrderBindingSource.DataSource = AttachmentWorkOrder_BLL.GetDataByworkOrderID(workOrder.WorkOrder_ID, isChangedAJ);
                    isChangedAJ = false;
                }
                e.Handled = true;
            }
            
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewAJ_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            statusAttachmentworkOrder = Status.New;
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewAJ_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = (GridView)sender;
            GridColumn AttachName = view.Columns["Name"];
            GridColumn AttachCode = view.Columns["Code"];
            GridColumn AttachContent = view.Columns["ContentFile"];

            if (null == view.GetRowCellValue(e.RowHandle, AttachName))
            {
                e.Valid = false;
                view.FocusedColumn = AttachName;
                e.ErrorText = "Please enter the Attachment Name. ";
                view.SetColumnError(AttachName, "Attachment Name is not empty");
            }
            if (null == view.GetRowCellValue(e.RowHandle, AttachCode))
            {
                e.Valid = false;
                view.FocusedColumn = AttachCode;
                e.ErrorText = "Please enter the Attachment Code. ";
                view.SetColumnError(AttachCode, "Attachment Code is not empty");
            }
            if (null == view.GetRowCellValue(e.RowHandle, AttachContent))
            {
                e.Valid = false;
                e.ErrorText = "Please upload one file into table ";
            }
            attachmentworkOrder = attachmentWorkOrderBindingSource.Current as AttachmentWorkOrder;
            WorkOrder j = workOrderBindingSource.Current as WorkOrder;
            attachmentworkOrder.WorkOrder_ID = j.WorkOrder_ID;
            if (TestBeforeInsertAttachworkOrder(attachmentworkOrder.Code))
            {
                e.Valid = false;
                view.FocusedColumn = AttachCode;
                e.ErrorText = "Attachment Code is exits. ";
                view.SetColumnError(AttachCode, "Attachment Code is exits");
            }
        }

        private bool TestBeforeInsertAttachworkOrder(string code)
        {
            int Count = 0;
            for (int i = 0; i < attachmentWorkOrderBindingSource.Cast<AttachmentWorkOrder>().ToList().Count; i++ )
            {
                if (attachmentWorkOrderBindingSource.Cast<AttachmentWorkOrder>().ToList()[i].Code == code)
                {
                    Count++;
                }
            }
            if (Count >= 2)
                return true;

            return false;
        }

        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewAJ_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl12.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    gridView18.DeleteSelectedRows();
                }
            }
        }

        // Đặt lại trạng thái update 
        private void gridViewAJ_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusAttachmentworkOrder = Status.Update;
            }
        }
        #endregion
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void gridControl12_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.CancelEdit:
                    DeleteAttachmentworkOrder(e);
                    break;
            }
        }

        private void sC_IDGridLookUpEdit_QueryPopUp(object sender, CancelEventArgs e)
        {
            if (serviceCodeBindingSource.Count == 0)
            {
                serviceCodeBindingSource.DataSource = ServiceCode_BLL.GetAll(frmMain.ship.Ship_ID);
            }
        }

        private void respDescipline_IDGridLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {
            try
            {
                workOrder.Employee = BaseDAL.DB.Employees.Single(n => n.Employee_ID == (int)e.NewValue);
            }
            catch { }
        }

        private void sC_IDGridLookUpEdit_EditValueChanging(object sender, ChangingEventArgs e)
        {
            try
            {
                workOrder.ServiceCode = BaseDAL.DB.ServiceCodes.Single(n => n.SC_ID == (int)e.NewValue);
            }
            catch { }
        }

    }
}